<template>
  <div class="category-management">
    <div class="page-header">
      <div class="header-left">
        <h1>分类管理</h1>
        <p>管理众筹项目的内容分类</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="openForm()">
          <el-icon><Plus /></el-icon>
          新增分类
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索分类名称..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 分类表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="paginatedCategories"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        default-expand-all
      >
        <el-table-column prop="name" label="分类名称" min-width="200"></el-table-column>
        <el-table-column prop="projectCount" label="项目数" width="120" align="center"></el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="100" align="center"></el-table-column>
        
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'danger'" size="small">
              {{ row.status === 'enabled' ? '已启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="openForm(row)">编辑</el-button>
            <el-button 
              :type="row.status === 'enabled' ? 'warning' : 'success'" 
              size="small" 
              link 
              @click="toggleStatus(row)"
            >
              {{ row.status === 'enabled' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" link @click="deleteCategory(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="filteredCategories.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="showForm"
      :title="isEdit ? '编辑分类' : '新增分类'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" ref="categoryForm" label-width="100px" :rules="rules">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" placeholder="请输入排序"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            active-text="启用"
            inactive-text="禁用"
            active-value="enabled"
            inactive-value="disabled"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showForm = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const showForm = ref(false)
const isEdit = ref(false)
const categoryForm = ref(null)

const form = reactive({
  id: null,
  name: '',
  sortOrder: 0,
  status: 'enabled'
})

const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

const categories = ref([
  { id: 1, name: '科技', projectCount: 25, sortOrder: 1, status: 'enabled', createTime: '2023-01-15 10:00:00' },
  { id: 2, name: '设计', projectCount: 18, sortOrder: 2, status: 'enabled', createTime: '2023-01-16 11:30:00' },
  { id: 3, name: '艺术', projectCount: 32, sortOrder: 3, status: 'enabled', createTime: '2023-01-17 14:00:00' },
  { id: 4, name: '美食', projectCount: 15, sortOrder: 4, status: 'disabled', createTime: '2023-01-18 16:45:00' },
  { id: 5, name: '游戏', projectCount: 40, sortOrder: 5, status: 'enabled', createTime: '2023-01-19 09:20:00' }
])

const filteredCategories = computed(() => {
  return categories.value.filter(cat => 
    cat.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

const paginatedCategories = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCategories.value.slice(start, end)
})

const handleSearch = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const openForm = (category = null) => {
  if (category) {
    isEdit.value = true
    Object.assign(form, category)
  } else {
    isEdit.value = false
    Object.assign(form, { id: null, name: '', sortOrder: 0, status: 'enabled' })
  }
  showForm.value = true
}

const submitForm = async () => {
  if (!categoryForm.value) return
  await categoryForm.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        const index = categories.value.findIndex(c => c.id === form.id)
        if (index !== -1) {
          categories.value[index] = { ...categories.value[index], ...form }
        }
        ElMessage.success('更新成功')
      } else {
        const newCategory = {
          ...form,
          id: Date.now(),
          projectCount: 0,
          createTime: new Date().toLocaleString('zh-CN')
        }
        categories.value.unshift(newCategory)
        ElMessage.success('新增成功')
      }
      showForm.value = false
    }
  })
}

const toggleStatus = (category) => {
  category.status = category.status === 'enabled' ? 'disabled' : 'enabled'
  ElMessage.success('状态更新成功')
}

const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const index = categories.value.findIndex(c => c.id === category.id)
    if (index !== -1) {
      categories.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消操作
  }
}

onMounted(() => {
  console.log('分类管理页面已加载')
})
</script>

<style scoped>
.category-management {
  max-width: 1200px;
  margin: 0 auto;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.header-left h1 {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}
.header-left p {
  color: #666;
  font-size: 14px;
}
.filter-card, .table-card {
  margin-bottom: 24px;
  border-radius: 12px;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}
</style> 